// 市场数据管理器
class MarketDataManager {
  constructor() {
    this.currentSymbol = 'sh600000'; // 默认股票代码
  }

  // 获取最新数据
  async getLatestData() {
    try {
      const result = await invoke('get_realtime_data', { symbol: this.currentSymbol });
      return this.processRealtimeData(JSON.parse(result));
    } catch (error) {
      console.error('获取实时数据失败:', error);
      throw error;
    }
  }

  // 获取历史数据
  async getHistoricalData(symbol, timeframe, startTime = null, endTime = null) {
    try {
      params = {
        symbol: symbol || this.currentSymbol,
        timeframe: timeframe || '1d',
        start_time: startTime,
        end_time: endTime,
        limit: 100
      }
      const result = await invoke('get_historical_data', { params: params });
      return this.processHistoricalData(JSON.parse(result));
    } catch (error) {
      console.error('获取历史数据失败:', error);
      throw error;
    }
  }

  // 获取特定时间尺度数据
  async getTimeframeData(timeframe) {
    try {
      const result = await this.getHistoricalData(this.currentSymbol, timeframe);
      return result;
    } catch (error) {
      console.error('获取时间尺度数据失败:', error);
      throw error;
    }
  }

  // 处理实时数据
  processRealtimeData(data) {
    return {
      klineData: data.candles.map(candle => [
        candle.open, candle.close, candle.low, candle.high
      ]),
      ma5: this.calculateMovingAverage(data.candles, 5),
      ma10: this.calculateMovingAverage(data.candles, 10),
      ma20: this.calculateMovingAverage(data.candles, 20),
      volumeData: data.candles.map(candle => candle.volume),
      trend: data.trend || 'neutral',
      strength: data.strength || 50,
    };
  }

  // 处理历史数据
  processHistoricalData(data) {
    return {
      klineData: data.candles.map(candle => [
        candle.open, candle.close, candle.low, candle.high
      ]),
      ma5: this.calculateMovingAverage(data.candles, 5),
      ma10: this.calculateMovingAverage(data.candles, 10),
      ma20: this.calculateMovingAverage(data.candles, 20),
      volumeData: data.candles.map(candle => candle.volume),
      trend: data.trend || 'neutral',
      strength: data.strength || 50,
    };
  }

  // 计算移动平均线
  calculateMovingAverage(data, period) {
    const result = [];
    for (let i = period - 1; i < data.length; i++) {
      const slice = data.slice(i - period + 1, i + 1);
      const avg = slice.reduce((sum, candle) => sum + candle.close, 0) / period;
      result.push([data[i].timestamp, avg]);
    }
    return result;
  }

  // 设置当前股票代码
  setCurrentSymbol(symbol) {
    this.currentSymbol = symbol;
  }
}

// 市场分析控制器
class MarketAnalysisController {
  constructor() {
    this.charts = {};
    this.dataManager = new MarketDataManager();
    this.updateInterval = null;
    this.predictionSystem = new PredictionSystem();
    this.riskControl = new RiskControl();
  }

  // 初始化图表
  initCharts() {
    this.charts.main = echarts.init(document.getElementById('main-chart'));
    this.setupMainChart();
    this.setupEventListeners();
    this.startRealTimeUpdate();
  }

  // 设置主图表
  setupMainChart() {
    const option = {
      grid: {
        left: '10%',
        right: '10%',
        bottom: '15%'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['K线', 'MA5', 'MA10', 'MA20', 'Volume']
      },
      xAxis: {
        type: 'time',
        boundaryGap: false
      },
      yAxis: [
        {
          type: 'value',
          scale: true,
          splitArea: {
            show: true
          }
        },
        {
          type: 'value',
          scale: true,
          splitArea: {
            show: true
          }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          start: 50,
          end: 100
        },
        {
          show: true,
          type: 'slider',
          bottom: '5%',
          start: 50,
          end: 100
        }
      ],
      series: [
        {
          name: 'K线',
          type: 'candlestick',
          data: []
        },
        {
          name: 'MA5',
          type: 'line',
          data: []
        },
        {
          name: 'MA10',
          type: 'line',
          data: []
        },
        {
          name: 'MA20',
          type: 'line',
          data: []
        },
        {
          name: 'Volume',
          type: 'bar',
          yAxisIndex: 1,
          data: []
        }
      ]
    };

    this.charts.main.setOption(option);
  }

  // 设置事件监听器
  setupEventListeners() {
    window.addEventListener('resize', () => {
      Object.values(this.charts).forEach(chart => chart.resize());
    });

    // 时间尺度切换
    document.querySelectorAll('[data-timeframe]').forEach(button => {
      button.addEventListener('click', (e) => {
        const timeframe = e.target.dataset.timeframe;
        this.changeTimeframe(timeframe);
      });
    });
  }

  // 开始实时更新
  startRealTimeUpdate() {
    this.updateInterval = setInterval(() => {
      this.updateMarketData();
      this.updatePredictions();
      this.updateRiskMetrics();
    }, 1000);
  }

  // 更新市场数据
  async updateMarketData() {
    try {
      const data = await this.dataManager.getLatestData();
      this.updateCharts(data);
      this.updateMarketState(data);
    } catch (error) {
      console.error('Failed to update market data:', error);
    }
  }

  // 更新预测
  async updatePredictions() {
    try {
      const predictions = await this.predictionSystem.getLatestPredictions();
      this.updatePredictionDisplay(predictions);
    } catch (error) {
      console.error('Failed to update predictions:', error);
    }
  }

  // 更新风险指标
  async updateRiskMetrics() {
    try {
      const riskMetrics = await this.riskControl.calculateRiskMetrics();
      this.updateRiskDisplay(riskMetrics);
    } catch (error) {
      console.error('Failed to update risk metrics:', error);
    }
  }

  // 更新图表数据
  updateCharts(data) {
    const option = this.charts.main.getOption();
    
    // 更新K线数据
    option.series[0].data = data.klineData;
    
    // 更新均线数据
    option.series[1].data = data.ma5;
    option.series[2].data = data.ma10;
    option.series[3].data = data.ma20;
    
    // 更新成交量数据
    option.series[4].data = data.volumeData;
    
    this.charts.main.setOption(option);
  }

  // 更新市场状态显示
  updateMarketState(data) {
    const stateElements = {
      trend: document.getElementById('market-trend'),
      strength: document.getElementById('market-strength'),
      volatility: document.getElementById('market-volatility'),
      momentum: document.getElementById('market-momentum')
    };

    if (stateElements.trend) {
      stateElements.trend.textContent = data.trend;
      stateElements.trend.className = `text-${data.trend === 'up' ? 'green' : 'red'}-600`;
    }

    if (stateElements.strength) {
      stateElements.strength.textContent = `${data.strength}%`;
    }

    // 更新其他状态显示...\
  }

  // 更新预测显示
  updatePredictionDisplay(predictions) {
    const predictionElements = {
      shortTerm: document.getElementById('short-term-prediction'),
      mediumTerm: document.getElementById('medium-term-prediction'),
      longTerm: document.getElementById('long-term-prediction')
    };

    // 更新短期预测
    if (predictionElements.shortTerm) {
      predictionElements.shortTerm.innerHTML = `
        <div class="flex items-baseline">
          <div class="text-2xl font-semibold ${predictions.shortTerm.direction === 'up' ? 'text-green-600' : 'text-red-600'}">
            ${predictions.shortTerm.direction === 'up' ? '+' : '-'}${predictions.shortTerm.probability}%
          </div>
          <div class="ml-2 text-sm text-gray-500">
            置信度: ${predictions.shortTerm.confidence}%
          </div>
        </div>
      `;
    }

    // 更新其他时间周期的预测...
  }

  // 更新风险指标显示
  updateRiskDisplay(metrics) {
    const riskElements = {
      stopLoss: document.getElementById('stop-loss'),
      takeProfit: document.getElementById('take-profit'),
      position: document.getElementById('recommended-position'),
      maxDrawdown: document.getElementById('max-drawdown')
    };

    if (riskElements.stopLoss) {
      riskElements.stopLoss.textContent = `¥${metrics.stopLoss.price}`;
    }

    if (riskElements.takeProfit) {
      riskElements.takeProfit.textContent = `¥${metrics.takeProfit.price}`;
    }

    // 更新其他风险指标显示...
  }

  // 切换时间尺度
  changeTimeframe(timeframe) {
    // 更新时间尺度按钮状态
    document.querySelectorAll('[data-timeframe]').forEach(button => {
      button.classList.remove('bg-blue-600', 'text-white');
      button.classList.add('bg-gray-100', 'text-gray-700');
    });

    const activeButton = document.querySelector(`[data-timeframe="${timeframe}"]`);
    if (activeButton) {
      activeButton.classList.remove('bg-gray-100', 'text-gray-700');
      activeButton.classList.add('bg-blue-600', 'text-white');
    }

    // 重新加载对应时间尺度的数据
    this.loadTimeframeData(timeframe);
  }

  // 加载特定时间尺度的数据
  async loadTimeframeData(timeframe) {
    try {
      const data = await this.dataManager.getTimeframeData(timeframe);
      this.updateCharts(data);
    } catch (error) {
      console.error('Failed to load timeframe data:', error);
    }
  }

  // 清理资源
  destroy() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
    Object.values(this.charts).forEach(chart => chart.dispose());
  }
}

// 预测系统类
class PredictionSystem {
  async getLatestPredictions() {
    // 实现预测逻辑
    return {
      shortTerm: {
        direction: 'up',
        probability: 75,
        confidence: 87
      },
      mediumTerm: {
        direction: 'up',
        probability: 65,
        confidence: 75
      },
      longTerm: {
        direction: 'up',
        probability: 55,
        confidence: 62
      }
    };
  }
}

// 风险控制类
class RiskControl {
  async calculateRiskMetrics() {
    // 实现风险计算逻辑
    return {
      stopLoss: {
        price: 41.80,
        percentage: 2
      },
      takeProfit: {
        price: 44.20,
        percentage: 3
      },
      position: {
        recommended: 20,
        maxRisk: 25
      },
      maxDrawdown: 3.2
    };
  }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  window.marketAnalysis = new MarketAnalysisController();
  window.marketAnalysis.initCharts();
});